<template>
  <div>
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="视频类型">
          <el-select v-model="searchForm.typeId" placeholder="请选择视频类型" clearable style="width: 200px;">
            <el-option
                v-for="item in typeOptions"
                :key="item.typeId"
                :label="item.typeName"
                :value="item.typeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="success" @click="handleAddVideo">发布视频</el-button>
    </div>

    <!-- 视频表格 -->
    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column prop="videoId" label="视频ID" width="80"/>
      <el-table-column prop="title" label="标题" show-overflow-tooltip/>
      <el-table-column prop="description" label="描述" show-overflow-tooltip/>
      <el-table-column prop="typeName" label="类型" width="120"/>
      <el-table-column prop="createdAt" label="发布时间" width="180"/>
      <el-table-column prop="updatedAt" label="更新时间" width="180"/>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEditVideo(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeleteVideo(scope.row.videoId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑视频对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="90%">
      <div class="dialog-content">
        <!-- 左侧视频编辑 -->
        <div class="video-edit">
          <el-form :model="currentForm" :rules="rules" ref="videoFormRef">
            <el-form-item label="标题" prop="title">
              <el-input v-model="currentForm.title" placeholder="请输入标题"/>
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input type="textarea" v-model="currentForm.description" placeholder="请输入视频描述"/>
            </el-form-item>
            <el-form-item label="视频类型" prop="typeId">
              <el-select v-model="currentForm.typeId" placeholder="请选择视频类型">
                <el-option
                    v-for="item in typeOptions"
                    :key="item.typeId"
                    :label="item.typeName"
                    :value="item.typeId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="视频文件" prop="videoUrl">
              <el-upload
                  class="video-uploader"
                  :action="uploadUrl"
                  :show-file-list="false"
                  :on-success="handleVideoSuccess"
                  :before-upload="beforeVideoUpload"
                  :on-error="handleVideoError"
              >
                <video v-if="currentForm.videoUrl" :src="currentForm.videoUrl" class="video-preview"/>
                <el-icon v-else class="video-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
        <!-- 右侧评论列表 -->
        <div class="comment-list" v-if="dialogTitle === '编辑视频'">
          <div class="comment-header">
            <h3>评论列表</h3>
            <el-button type="primary" size="small" @click="fetchComments">刷新</el-button>
          </div>
          <el-table :data="commentList" border style="width: 100%;">
            <el-table-column prop="content" label="评论内容" show-overflow-tooltip/>
            <el-table-column prop="createdTime" label="评论时间" width="180"/>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button type="danger" size="small" @click="handleDeleteComment(scope.row.replyId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Plus} from '@element-plus/icons-vue';
import {
  videoCommentDeleteOne,
  videoCommentSelectList,
  videoDeleteOne,
  videoInsertOne,
  videoSelectPage,
  videoUpdateOne,
  videoTypeSelectList
} from "@/api/material.js";
import {BaseURL} from "@/utils/http.js";

const uploadUrl = ref(BaseURL + '/upload');

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 视频类型选项
const typeOptions = ref([]);

// 搜索条件
const searchForm = reactive({
  typeId: null,
});

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const currentForm = reactive({
  videoId: null,
  title: '',
  description: '',
  videoUrl: '',
  typeId: null,
  createdAt: '',
  updatedAt: '',
});
const videoFormRef = ref(null);

// 验证规则
const rules = {
  title: [
    {required: true, message: '标题不能为空', trigger: 'blur'},
    {min: 2, max: 50, message: '标题长度在2到50个字符之间', trigger: 'blur'}
  ],
  description: [
    {required: true, message: '描述不能为空', trigger: 'blur'},
    {min: 10, message: '描述长度不能少于10个字符', trigger: 'blur'}
  ],
  typeId: [
    {required: true, message: '请选择视频类型', trigger: 'change'}
  ],
  videoUrl: [
    {required: true, message: '请上传视频文件', trigger: 'change'}
  ],
};

// 评论列表数据
const commentList = ref([]);

// 获取视频类型列表
const fetchVideoTypes = async () => {
  try {
    const response = await videoTypeSelectList();
    typeOptions.value = response.data.records;
  } catch (error) {
    ElMessage.error('获取视频类型列表失败');
  }
};

// 获取视频列表
const fetchVideos = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      typeId: searchForm.typeId
    };
    if (!params.typeId) {
      delete params.typeId;
    }
    const response = await videoSelectPage(params);
    tableData.value = response.data.records;
    total.value = response.data.total;
  } catch (error) {
    ElMessage.error('获取视频列表失败');
  }
};

// 新增视频
const handleAddVideo = () => {
  dialogTitle.value = '发布视频';
  dialogVisible.value = true;
  resetForm();
};

// 编辑视频
const handleEditVideo = (row) => {
  dialogTitle.value = '编辑视频';
  dialogVisible.value = true;
  Object.assign(currentForm, row);
  // 获取评论列表
  fetchComments();
};

// 删除视频
const handleDeleteVideo = (videoId) => {
  ElMessageBox.confirm('确认删除该视频?', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await videoDeleteOne(videoId);
      ElMessage.success('删除成功');
      await fetchVideos();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

// 保存视频（新增/编辑）
const handleSubmit = () => {
  videoFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (currentForm.videoId) {
          // 编辑
          await videoUpdateOne(currentForm);
        } else {
          // 新增
          await videoInsertOne(currentForm)
        }
        ElMessage.success('保存成功');
        dialogVisible.value = false;
        await fetchVideos();
      } catch (error) {
        ElMessage.error('保存失败');
      } finally {
        resetForm();
      }
    }
  });
};

// 分页事件
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchVideos();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchVideos();
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchVideos();
};

// 重置搜索
const resetSearch = () => {
  currentPage.value = 1;
  searchForm.typeId = null;
  fetchVideos();
};

// 重置表单
const resetForm = () => {
  Object.assign(currentForm, {
    videoId: null,
    title: '',
    description: '',
    videoUrl: '',
    typeId: null,
    createdAt: '',
    updatedAt: '',
  });
  videoFormRef.value?.clearValidate();
};

// 获取评论列表
const fetchComments = async () => {
  try {
    const response = await videoCommentSelectList({
      videoId: currentForm.videoId,
    });
    commentList.value = response.data;
  } catch (error) {
    ElMessage.error('获取评论列表失败');
  }
};

// 删除评论
const handleDeleteComment = (replyId) => {
  ElMessageBox.confirm('确认删除该评论?', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await videoCommentDeleteOne(replyId);
      ElMessage.success('删除成功');
      await fetchComments();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

// 视频上传相关方法
const handleVideoSuccess = (response) => {
  if (response.code === 200) {
    currentForm.videoUrl = response.data;
    ElMessage.success('视频上传成功');
  } else {
    ElMessage.error('视频上传失败');
  }
};

const handleVideoError = () => {
  ElMessage.error('视频上传失败');
};

const beforeVideoUpload = (file) => {
  const isVideo = file.type.startsWith('video/');
  const isLt500M = file.size / 1024 / 1024 < 500;

  if (!isVideo) {
    ElMessage.error('只能上传视频文件!');
    return false;
  }
  if (!isLt500M) {
    ElMessage.error('视频大小不能超过 500MB!');
    return false;
  }
  return true;
};

// 初始化数据
onMounted(() => {
  fetchVideoTypes();
  fetchVideos();
});
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
}

.action-bar {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-content {
  display: flex;
  gap: 20px;
}

.video-edit {
  flex: 1;
}

.comment-list {
  width: 500px;
  border-left: 1px solid #dcdfe6;
  padding-left: 20px;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.comment-header h3 {
  margin: 0;
}

.video-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 360px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.video-uploader:hover {
  border-color: #409EFF;
}

.video-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 360px;
  height: 200px;
  text-align: center;
  line-height: 200px;
}

.video-preview {
  width: 360px;
  height: 200px;
  object-fit: cover;
}
</style>
